package com.learn.acm.netty.protobuf1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 *
 */
@Slf4j
public class NettyClientHandler extends SimpleChannelInboundHandler<DataOuterClass.Data> {


    /**
     * 当通道就绪就会触发该方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        log.info("-client-->{}", ctx.toString());
        DataOuterClass.Data data = DataOuterClass.Data.newBuilder().setName("小白").setAge(12).setDesc("").build();
//        ctx.writeAndFlush(Unpooled.copiedBuffer("hello server ~~", CharsetUtil.UTF_8));
        ctx.writeAndFlush(data);
    }

    /**
     * 当通道有读取事件时会触发
     * @param ctx 上下文
     * @param msg 读取到的消息
     * @throws Exception
     */
    @Override
    public void channelRead0(ChannelHandlerContext ctx, DataOuterClass.Data msg) throws Exception {

        log.info("服务器回复的消息：{}, age={},extend={}", msg.getName(),msg.getAge(),msg.getExtend());
        log.info("服务器的地址：{}", ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
